<template>
  <el-card>
    <el-container style="flex-direction:column;">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" size="small">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="commodityName">
              <el-input v-model="form.commodityName" autocomplete="off" placeholder="请输入商品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店选择" prop="storeId">
              <el-select clearable v-model="form.storeId" placeholder="请选择门店">
                <el-option
                  v-for="item in storeList"
                  :key="item.storeId"
                  :label="item.name"
                  :value="item.storeId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品规格" prop="isMultiSpecification">
          <el-radio-group v-model="form.isMultiSpecification">
            <el-radio :label="0">单规格</el-radio>
            <el-radio :label="1">多规格</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="form.isMultiSpecification == 1">
          <el-row>
            <el-col :span="12">
              <div style="display:flex;">
                <div style="flex:1">
                  <el-form-item label="选择规格">
                    <el-select clearable v-model="form.specificationsId" placeholder="请选择规格">
                      <el-option
                        v-for="item in specificationsList"
                        :key="item.specificationsId"
                        :label="item.name"
                        :value="item.specificationsId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div style="flex-basis:auto;">
                  <el-button type="primary" size="small" @click="specificationsChange">确定</el-button>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label>
              <div
                v-for="item, index in activeSpecifications.typeGroupDTOList"
                :key="index"
                style="display: flex;flex-direction:column;"
              >
                <div style="display: flex;align-items: center;">{{ item.typeGroupName }}</div>
                <div style="display: flex;">
                  <el-tag
                    style="margin-right:10px;"
                    v-for="citem in item.groupValueList"
                    :key="citem.groupValueName"
                    :disable-transitions="false"
                  >{{ citem.groupValueName }}</el-tag>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="" v-if="activeSpecifications.typeGroupDTOList && activeSpecifications.typeGroupDTOList.length != 0">
              <el-button
                type="success"
                size="small"
                @click="generateIsMultiSpecificationCommodityDetailsData"
              >立即生成</el-button>
            </el-form-item>
          </el-row>
          <el-form-item label v-if="showMultiSpecificationCommodityDetailsTable">
            <el-table size="mini" :data="isMultiSpecificationCommodityDetails" style="width: 100%">
              <el-table-column
                v-for="item, index in tableSpecifications.typeGroupDTOList"
                :key="item.typeGroupId"
                :label="item.typeGroupName"
              >
                <template slot-scope="scope">{{ scope.row.groupValueList[index].groupValueName }}</template>
              </el-table-column>
              <el-table-column prop="price" label="售价">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.price" autocomplete="off"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="cost" label="成本">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.cost" autocomplete="off"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="stock" label="库存">
                <template slot-scope="scope">
                  <el-input v-model.number="scope.row.stock" autocomplete="off"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="introduction" label="商品简介" width="200px">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.introduction" autocomplete="off"></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>
        <el-form-item label v-if="form.isMultiSpecification == 0">
          <el-table size="mini" :data="commodityDetails" style="width: 100%">
            <el-table-column prop="price" label="售价">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" autocomplete="off"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="cost" label="成本">
              <template slot-scope="scope">
                <el-input v-model="scope.row.cost" autocomplete="off"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存">
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.stock" autocomplete="off"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="introduction" label="商品简介" width="200px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.introduction" autocomplete="off"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="avatar-uploader"
            :action="baseURL + '/commodity/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.image" :src="baseURL + form.image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否上架" prop="isShow">
              <el-radio-group v-model="form.isShow">
                <el-radio :label="1">上架中</el-radio>
                <el-radio :label="0">待上架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品排序">
              <el-input-number
                style="width: 100%;"
                v-model="form.sort"
                controls-position="right"
                :min="1"
                :max="999"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-container>
  </el-card>
</template>
<script>
import { baseURL } from '@/utils/setting.js'
import { getUserHaveOrBelongToStore } from '@/api/modules/StoreManagement/storeList.js'
import { getAllSpecifications } from '@/api/modules/CommodityManagement/commodityRule.js'
import { addCommodity } from '@/api/modules/CommodityManagement/manageGoods.js'
export default {
  data() {
    return {
      storeList: [],
      form: {
        "storeId": null,
        "specificationsId": null,
        "image": "",
        "commodityName": null,
        "isShow": 0,
        "sort": null,
        "isMultiSpecification": 0,
      },
      rules: {
        commodityName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        storeId: [
          { required: true, message: '请选择商品所属门店', trigger: 'change' }
        ]
      },
      commodityDetails: [{
        price: 0, cost: 0, stock: 0, introduction: ""
      }],
      isMultiSpecificationCommodityDetails: [],
      specificationsList: [],
      activeSpecifications: {},
      showMultiSpecificationCommodityDetailsTable: false,
      tableSpecifications: {},
    }
  },
  computed: {
    baseURL() { return baseURL },
  },
  created() {
    this.getUserHaveOrBelongToStore()
    this.getAllSpecifications()
  },
  methods: {
    generateIsMultiSpecificationCommodityDetailsData() {
      this.showMultiSpecificationCommodityDetailsTable = true;
      let data = JSON.parse(JSON.stringify(this.activeSpecifications));
      this.tableSpecifications = data
      let arr = data.typeGroupDTOList

      let result = { groupValueList: [] }
      let results = []
      this.doExchange1(arr, 0, result, results);
      this.isMultiSpecificationCommodityDetails = results;
    },
    doExchange1(arr, depth, result, results) {
      for (var i = 0; i < arr[depth].groupValueList.length; i++) {
        result.groupValueList[depth] = arr[depth].groupValueList[i]
        if (depth != arr.length - 1) {
          this.doExchange1(arr, depth + 1, result, results)
        } else {
          results.push({ ...JSON.parse(JSON.stringify(result)), ...{ price: 0, cost: 0, stock: 0, introduction: "" } })
        }
      }
    },
    specificationsChange() {
      const data = this.specificationsList;
      for (let o of data) {
        if (o.specificationsId == this.form.specificationsId) {
          this.activeSpecifications = JSON.parse(JSON.stringify(o))
          break;
        }
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          let data = JSON.parse(JSON.stringify(this.form))
          if (data.isMultiSpecification == 0) {
            data.specificationsId = null
            data.commodityDetailsDTOList = this.commodityDetails
          } else {
            data.specificationsId = this.tableSpecifications.specificationsId
            data.commodityDetailsDTOList = this.isMultiSpecificationCommodityDetails
          }
          addCommodity(data).then(() => {
            this.commodityDetails = [{
              price: 0, cost: 0, stock: 0, introduction: ""
            }]
            this.resetForm("ruleForm")
            this.showMultiSpecificationCommodityDetailsTable = false
            this.activeSpecifications = {}
            this.isMultiSpecificationCommodityDetails = []
            this.form.specificationsId = null
            this.form.image = ""
          })
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleAvatarSuccess(res) {
      // console.log(res)
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.form.image = res.data
    },
    beforeAvatarUpload(file) {
      // console.log(file)
      let data = ['image/png', 'image/jpeg'];
      if (!data.includes(file.type)) {
        this.$message.error('上传商品分类图片只能是 png或JPG 格式!');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传商品分类图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    getUserHaveOrBelongToStore() {
      getUserHaveOrBelongToStore().then(res => {
        this.storeList = res.data.data
      })
    },
    getAllSpecifications() {
      getAllSpecifications().then(res => {
        this.specificationsList = res.data.data
      })
    }
  }
}
</script>
<style scoped>
.el-select {
  width: 100%;
}
.avatar-uploader >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader >>> .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>